package com.gzu.finalwork.user.service;

import com.gzu.finalwork.user.config.AjaxResult;
import com.gzu.finalwork.entity.user.DeliveryOrders;
import com.gzu.finalwork.user.mapper.DeliveryOrdersMapper;
import com.gzu.finalwork.courier.mapper.CourierMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

@Service
public class DeliveryOrdersService {
    @Autowired
    private DeliveryOrdersMapper deliveryOrdersMapper;
    // 在创建订单时同时创建轨迹
    @Autowired
    private DeliveryTrackService deliveryTrackService;
    //创建订单的同时更新地址的统计信息
    @Autowired
    AddressStatsService addressStatsService;
    
    @Autowired
    private CourierMapper courierMapper;

    private static final Random RANDOM = new Random();
    private static final String ORDER_PREFIX = "CRD";
    // 创建订单
    public Object createDeliveryOrders(DeliveryOrders deliveryOrders){
        String orderNumber = generateOrderNumber();
        deliveryOrders.setOrderNumber(orderNumber);
        deliveryOrders.setOrderStatus(0);
        deliveryOrdersMapper.createDeliveryOrders(deliveryOrders);
        DeliveryOrders deliveryOrders1 = deliveryOrdersMapper.selectByDeliveryOrderNo(deliveryOrders.getOrderNumber());
        deliveryTrackService.createTrack(deliveryOrders1.getDeliveryOrderId(), deliveryOrders1.getOrderNumber());
        System.out.println("创建订单成功");
        // 记录地址使用情况
        Long userId = deliveryOrders.getUserId();
        if (userId != null) {
            // 记录寄件地址
            if (deliveryOrders.getSenderAddress() != null) {
                addressStatsService.recordAddressUsage(userId,deliveryOrders.getSenderName(),deliveryOrders.getSenderPhone(), deliveryOrders.getSenderAddress());
            }
            // 记录收件地址
            if (deliveryOrders.getReceiverAddress() != null) {
                addressStatsService.recordAddressUsage(userId,deliveryOrders.getReceiverName(),deliveryOrders.getReceiverPhone(), deliveryOrders.getReceiverAddress());
            }
        }
        System.out.println("redis缓存更新成功");
        return AjaxResult.success("创建订单成功");
    }

    // 根据订单号获取订单详情
    public Object selectByDeliveryOrderId(Long deliveryOrderId){
        DeliveryOrders deliveryOrders = deliveryOrdersMapper.selectByDeliveryOrderId(deliveryOrderId);
        return AjaxResult.success(deliveryOrders);
    }

    //根据订单实体查询订单列表
    public List<DeliveryOrders> selectDeliveryOrdersList(DeliveryOrders deliveryOrders,int pageNum,int pageSize){
        int offset = (pageNum - 1) * pageSize;
        List<DeliveryOrders> deliveryOrdersList = deliveryOrdersMapper.selectByDeliveryOrders(deliveryOrders,pageSize, offset);
        return deliveryOrdersList;
    }

   //根据订单号删除订单
    @Transactional
    public Object deleteDeliveryOrder(Long deliveryOrderId){
        try {
            // 1. 先删除配送员的接单信息
            int assignmentDeleteResult = courierMapper.deleteAssignmentByOrderId(deliveryOrderId);
            
            // 2. 再删除订单
            int orderDeleteResult = deliveryOrdersMapper.deleteByDeliveryOrderId(deliveryOrderId);
            
            if (orderDeleteResult > 0) {
                return AjaxResult.success("删除订单成功，同时清理了 " + assignmentDeleteResult + " 条配送分配记录");
            } else {
                return AjaxResult.success("删除订单失败");
            }
        } catch (Exception e) {
            return AjaxResult.error(-1, "删除订单失败：" + e.getMessage());
        }
    }



    //获取用户的订单列表,根据订单状态
    // 获取用户的订单列表
    public List<DeliveryOrders> getDeliveryOrdersList(Long userId ,int pageNum, int pageSize){
        int offset = (pageNum - 1) * pageSize;
        List<DeliveryOrders> deliveryOrdersList = deliveryOrdersMapper.selectByUserId(userId, pageSize, offset);
        return deliveryOrdersList;
    }
    //获取用户的订单数量
    public Integer getDeliveryOrdersCountByUserId(Long userId){
        return deliveryOrdersMapper.selectCountByUserId(userId);
    }
    public Integer selectDeliveryOrdersCountByUserId(DeliveryOrders deliveryOrders){
        return deliveryOrdersMapper.selectCountByDeliveryOrders(deliveryOrders);
    }
    public Integer getDeliveryCountByUserId(Long userId,Integer orderStatus){
        return   deliveryOrdersMapper.selectCountByUserIdAndStatus(userId,orderStatus);
    }
    //获取用户的订单列表
    public List<DeliveryOrders> getDeliveryOrdersListByStatus(Long userId,int pageNum, int pageSize){
        int offset = (pageNum - 1) * pageSize;
        List<DeliveryOrders> deliveryOrdersList = deliveryOrdersMapper.selectStatusByUserId(userId, pageSize, offset);
        return deliveryOrdersList;
    }

    public  List<DeliveryOrders> getDeliveryProcessingList(Long userId,int pageNum, int pageSize){
        int offset = (pageNum - 1) * pageSize;
        List<DeliveryOrders> deliveryOrdersList = deliveryOrdersMapper.selectStatusProcessingByUserId(userId, pageSize, offset);
        return deliveryOrdersList;
    }
    public List<DeliveryOrders> getDeliveryDeliveryingList (Long userId,int pageNum, int pageSize){
        int offset = (pageNum - 1) * pageSize;
        List<DeliveryOrders> deliveryOrdersList = deliveryOrdersMapper.selectStatusDeliveryingByUserId(userId, pageSize, offset);
        return deliveryOrdersList;
    }
    public List<DeliveryOrders>  getDeliveryCompletedList (Long userId,int pageNum, int pageSize){
        int offset = (pageNum - 1) * pageSize;
        List<DeliveryOrders> deliveryOrdersList = deliveryOrdersMapper.selectStatusCompletedByUserId(userId, pageSize, offset);
        return deliveryOrdersList;
    }


    //获取是所有的待处理订单
    public Object selectStatusPending(){
        List<DeliveryOrders> deliveryOrdersList = deliveryOrdersMapper.selectStatusPending();
        return AjaxResult.success(deliveryOrdersList);
    }
    //获取是所有的处理中订单
    public Object selectStatusProcessing(Long delivererId){
        List<DeliveryOrders> deliveryOrdersList = deliveryOrdersMapper.selectStatusProcessing(delivererId);
        return AjaxResult.success(deliveryOrdersList);
    }

    //获取是所有的配送中订单
    public Object selectStatusDeliverying(Long delivererId){
        List<DeliveryOrders> deliveryOrdersList = deliveryOrdersMapper.selectStatusDeliverying(delivererId);
        return AjaxResult.success(deliveryOrdersList);
    }

    //获取是所有的已完成订单
    public Object selectStatusCompleted(Long delivererId){
        List<DeliveryOrders> deliveryOrdersList = deliveryOrdersMapper.selectStatusCompleted(delivererId);
        return AjaxResult.success(deliveryOrdersList);
    }

    //给订单增加配送员
    public  Object addDeliverer(Long deliveryOrderId, Long delivererId){
        DeliveryOrders deliveryOrders = deliveryOrdersMapper.selectByDeliveryOrderId(deliveryOrderId);
        deliveryOrders.setDelivererId(delivererId);
        deliveryOrders.setOrderStatus(2);
        deliveryOrders.setUpdatedAt(LocalDateTime.now());
        return AjaxResult.success(deliveryOrdersMapper.updateStatusByDeliveryOrderId(deliveryOrders));
    }

    //改变订单状态,配送按钮
    public  Object setProcessing(Long deliveryOrderId){
        DeliveryOrders deliveryOrders = deliveryOrdersMapper.selectByDeliveryOrderId(deliveryOrderId);
        deliveryOrders.setOrderStatus(3);
        deliveryOrders.setUpdatedAt(LocalDateTime.now());
        return AjaxResult.success(deliveryOrdersMapper.updateStatusByDeliveryOrderId(deliveryOrders));
    }
    //改变订单状态,到达按钮
    public  Object setDeliverying(Long deliveryOrderId){
        DeliveryOrders deliveryOrders = deliveryOrdersMapper.selectByDeliveryOrderId(deliveryOrderId);
        deliveryOrders.setOrderStatus(4);
        deliveryOrders.setUpdatedAt(LocalDateTime.now());
        return AjaxResult.success(deliveryOrdersMapper.updateStatusByDeliveryOrderId(deliveryOrders));
    }

    //用于test,测试
    public Object test(Long deliveryOrderId){
        DeliveryOrders deliveryOrders = deliveryOrdersMapper.selectByDeliveryOrderId(deliveryOrderId);
        deliveryOrders.setOrderStatus(1);
        return AjaxResult.success(deliveryOrdersMapper.updateStatusByDeliveryOrderId(deliveryOrders));
    }




    // 生成订单编号
    public String generateOrderNumber() {
        String timestamp = LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));

        int randomNum = RANDOM.nextInt(9000) + 1000;

        return ORDER_PREFIX + timestamp + randomNum;
    }
}
